import { ref } from 'vue'
import { ArticeApi } from './api'
import { ConfigClass } from './config'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export class ArticleClass {
	configClass: ConfigClass
	baseData = ref()
	total = ref(0)
	selection = ref([])
	public query = ref()
	public router = useRouter()
	public visible = ref<boolean>(false)
	public src = ref()
	constructor() {
		this.configClass = new ConfigClass(this)
		this.getList()
	}

	/**
	 * 获取表格配置
	 */
	public getTableConfig() {
		return { ...this.configClass.tableConfig, data: this.baseData.value, total: this.total.value }
	}

	/**
	 * 查询配置
	 */
	public getSearchCol() {
		return this.configClass.searchCol
	}

	/**
	 * 查询
	 */
	public serach(query) {
		this.query.value = query
		this.configClass.tableConfig.pagination.currentPage = 1
		this.getList()
	}
	/**
	 * 获取表格数据
	 */
	public getList() {
		const params = {
			...this.query.value,
			currentPage: this.configClass.tableConfig.pagination.currentPage,
			pageSize: this.configClass.tableConfig.pagination.pageSize
		}
		ArticeApi.queryArticel(params).subscribe((res: any) => {
			const { records = [], total = 0 } = res
			this.baseData.value = [...records]
			this.total.value = total
		})
	}

	/**
	 * 新增文章
	 */
	public add() {
		this.router.push({ path: '/articleItem' })
	}

	/**
	 * 分页查询
	 */
	public onPageChange() {
		this.getList()
	}

	/**
	 * 删除文章
	 */
	public delete(id: number) {
		const params = {
			id: id
		}
		ArticeApi.deleteAtricle(params).subscribe(() => {
			ElMessage.success('删除成功')
			this.getList()
		})
	}

	/**
	 * 编辑文章
	 */
	public update(id: number) {
		this.router.push({
			path: `/articleItem`,
			query: {
				id: id
			}
		})
	}

	/**
	 * 查看封面
	 */
	public preview(img: string) {
		this.src.value = `http://ikun-pro-ui.fun:3000/static/${img}`
		this.visible.value = true
	}

	/**
	 * 批量删除
	 */
	public batchDelete() {
		const params = {
			ids: this.selection.value?.map(item => item.id) || []
		}
		ArticeApi.batchDel(params).subscribe(() => {
			ElMessage.success('删除成功')
			this.getList()
		})
	}

	/**
	 * 发布文章
	 */
	public publish(row) {
		const params = {
			...row
		}
		ArticeApi.publish(params).subscribe(() => {
			console.log(1)
		})
	}
}
